<script setup lang="ts">
import Bus from '@likg/bus';
import Validator from '@likg/validator';
import { showLoadingToast, showDialog, closeToast, showToast } from 'vant';
import Tools from "@likg/tools";
import Keybords from '@/components/keybords.vue';
import { useRouter ,useRoute} from 'vue-router';
import { api } from "@/api/apiServer";
import { useUserStore } from "@/stores/modules/user";
const env = Tools.getEnv();
const store = useUserStore();
const router = useRouter();
const route = useRoute();
import {
    reactive,
    ref,
    toRefs,
    watch,
    watchEffect,
    onMounted
} from 'vue';
interface StateProps {
    customerId: string | null,
    activateType: number[],
    activateText: string;
    phoneNumber: string,
    carNumber: string,
    idNumberSub6: string,
    realName: string,
    cardPwd:'',
    canBind: boolean;
    dialogShow: boolean;
    dialogPayShow:boolean;
    checked: any[];
    cartCode: string;
    cartCodeShow: boolean;
}

let columns:any[] = [
    // { text: '车牌号+身份证后6位', value: 1 },
    // { text: '车牌号+姓名', value: 2 },
    // { text: '身份证后6位+姓名', value: 3 },
];
const showPicker = ref(false);

const state = reactive<StateProps>({
    customerId: store.userId || route.query?.customerId as string || '',
    activateType: [],
    activateText: '',
    phoneNumber: '',
    carNumber: '',
    idNumberSub6: '',
    realName: '',
    cardPwd:'',

    canBind: false,
    dialogShow: false,
    dialogPayShow:false,
    checked: [],
    cartCode: '',
    cartCodeShow: false
});
// events
let payInfo:any = ref({});
const onBind = async () => {
    if (!state.canBind) {
        return;
    }
    if (state.checked.length == 0) {
        showToast({
            message: '请勾选用户协议'
        })
        return
    }
    showLoadingToast({
        message: '正在激活...'
    });
    let res = await api.activeUser({
        "customerId": state.customerId,
        "activateType": state.activateType[0],
        "carNumber": state.carNumber,
        "idNumberSub6": state.idNumberSub6,
        "realName": state.realName
    })
    closeToast();
    if (res.code === 200) {
        // 判断是否需要支付
        if (res.data.isPay) {
            // 显示确定弹框
            state.dialogPayShow = true;
            payInfo =  res.data.payInfo;
        } else {
            // 无需支付，直接领取积分或抵扣金
            getIntegral()
        }
    } else {
        showToast({
            message: res.msg as string || '激活失败！',
            icon: 'none'
        })
    }
};

// 卡密激活
const cardKeyActivateFn = async () => {
     if (!state.canBind) {
        return;
    }
    if (state.checked.length == 0) {
        showToast({
            message: '请勾选用户协议'
        })
        return
    }
    showLoadingToast({
        message: '正在激活...'
    });
    let res = await api.activeCardPwdUser({
        "customerId": state.customerId,
        "cardPassword": state.cardPwd
    })
    closeToast();
    if (res.code === 200) {
        checkUserActiveCard();
    } else {
        showToast({
            message: res.msg as string || '激活失败！',
            icon: 'none'
        })
    }
}

onMounted(()=>{
    // 获取路由参数
    let {type} = route.query;
    if(type === "1") {
        // 卡密激活
        columns = [{ text: '卡密验证', value: 4 }]
    } else {
        // 其它激活
        columns = [
            { text: '车牌号+身份证后6位', value: 1 },
            // { text: '车牌号+姓名', value: 2 },
            // { text: '身份证后6位+姓名', value: 3 },
        ]
    }
    state.activateText = columns[0].text
    state.activateType = [columns[0].value]

})

// 支付方法
const payFn = () => {
    state.dialogPayShow = false
    // 调用微信公众号支付
    WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                'appId': payInfo.packageParams.appId, //公众号ID，由商户传入
                'timeStamp': payInfo.packageParams.timeStamp, //时间戳，自1970年以来的秒数
                'nonceStr': payInfo.packageParams.nonceStr, //随机串
                'package': payInfo.packageParams.package,
                'signType': payInfo.packageParams.signType, //微信签名方式：
                'paySign': payInfo.packageParams.paySign //微信签名
            }, (res: any) => {
                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                    showToast({
                        message: '支付成功！',
                        icon: 'success',
                        onClose:()=>{
                            // 领取积分或抵扣金
                            getIntegral()
                        }
                    })
                } else {
                    showToast({
                        message: '支付失败！'
                    })
                }
            })
}

// 引取积分或抵扣金方法
const jifengData = ref();
const getIntegral = async () => {
    let res:any = await api.receivePoints({
        "customerId": state.customerId,
        "activateType": state.activateType[0],
        "carNumber": state.carNumber,
        "idNumberSub6": state.idNumberSub6,
        "realName": state.realName
    })
    console.log(res)
    if (res.code === 200) {
        jifengData.value = res.data;
        checkUserActiveFn()
        state.dialogShow = true
    } else {
        showToast({
            message: res.msg as string || '领取失败！',
            icon: 'none'
        })
    }
};

// 根据openid 验证用户是否激活
const checkUserActiveFn = async() => {
      let res:any = await api.checkUserIsActive({
        openId:store.wxOpenId as string
      });
      if(res.code === 200) {
        // 用户已创建已激活
          // 保存token
          localStorage.setItem("token", res.data.token.token);
          store.setToken(res.data.token.token);
      } else {
         showToast({
            message: '用户激活失败！',
            icon: 'none'
          })
      }
}




// 根据openid 验证用户是否激活
const checkUserActiveCard = async() => {
    let res:any = await api.checkUserIsActive({
        openId:store.wxOpenId as string
    });
    if(res.code === 200) {
        // 用户已创建已激活
        // 保存token
        localStorage.setItem("token", res.data.token.token);
        store.setToken(res.data.token.token);
        // 跳转首页
        router.replace("/");
    } else {
        showToast({
            message: '用户激活失败！',
            icon: 'none'
        })
    }
}

const onConfirm = ({ selectedValues, selectedOptions }: any) => {
    state.activateType = selectedValues;
    state.activateText = selectedOptions.map((item: any) => item.text).join(",");
    showPicker.value = false;
};

const onDialogClose = () => {
    state.dialogShow = false
    // 跳转首页
    router.replace("/");
};

// 关闭支付确定提示弹框
const onDialogPayClose = () => {
    state.dialogPayShow = false
}

const input_key = (val: any) => {
    if (val.isHid == true) {
        state.cartCodeShow = !val.isHid
    } else {
        state.cartCode = val.num
    }
    console.log(state.cartCode)
}

// watch
watchEffect(() => {
    switch (state.activateType[0]) {
        case 1:
            if (state.carNumber.length > 0 && state.idNumberSub6.length > 0) {
                state.canBind = true;
            } else {
                state.canBind = false;
            }
            break;
        case 2:
            if (state.carNumber.length > 0 && state.realName.length > 0) {
                state.canBind = true;
            } else {
                state.canBind = false;
            }
            break;
        case 3:
            if (state.idNumberSub6.length > 0 && state.realName.length > 0) {
                state.canBind = true;
            } else {
                state.canBind = false;
            }
            break;
        case 4:
             if (state.cardPwd.length > 0) {
                state.canBind = true;
            } else {
                state.canBind = false;
            }
            break
    }

});

const getcrNumber = (val: string) => {
    const carNumberReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
    if (carNumberReg.test(val)) {
        state.cartCodeShow = false
        state.carNumber = val;
    }
};
</script>

<template>
    <div class="page">
        <app-header v-if="env !== 'weixin'" title="激活验证" :showBack="true" :show-status-bar="false" />
        <div class="bind-phone">
            <van-field v-model="state.activateText" is-link readonly name="picker" label="验证方式" label-width="130"
                placeholder="点击选择验证方式" @click="showPicker = true" />
            <van-field v-model="state.carNumber" v-if="[1, 2].includes(state.activateType[0])" type="text"
                label-width="130" label="车牌号" clearable placeholder="请输入车牌号" readonly :border="false"
                :rules="[{ required: true, message: '请填写车牌号' }]"
                @click="state.cartCodeShow = !state.cartCodeShow"></van-field>
            <van-field v-model="state.realName" v-if="[2, 3].includes(state.activateType[0])" type="text"
                label-width="130" label="姓名" clearable placeholder="请输入姓名" :border="false"></van-field>
            <van-field v-model="state.idNumberSub6" v-if="[1, 3].includes(state.activateType[0])" type="text"
                label-width="130" label="身份证后6位" maxlength="6" clearable placeholder="请输入身份证后6位" :border="false"
                :rules="[{ required: true, message: '请填写身份证后6位' }]"></van-field>

                <van-field v-model="state.cardPwd" v-if="[4].includes(state.activateType[0])" type="text"
                label-width="130" label="卡密" clearable placeholder="请输入卡密" :border="false"></van-field>

            <div class="f14 mt-22 text-center " v-if="![4].includes(state.activateType[0])">
                <span style="color:#F59A23">提示：{{ $route.query?.customerId?'领取':'激活' }}时可能需要支付服务费</span>
            </div>
            <van-button v-if="![4].includes(state.activateType[0])" round block class="bind-btn" @click="onBind" :class="{ can: state.canBind }">
                {{ $route.query?.customerId?'立即领取':'激活验证' }}
            </van-button>

            <van-button v-if="[4].includes(state.activateType[0])" round block class="bind-btn" @click="cardKeyActivateFn" :class="{ can: state.canBind }">
                激活验证
            </van-button>


            <div class="f14 position-fixed" style="bottom:60px;">
                <van-checkbox-group v-model="state.checked" shape="square">
                    <van-checkbox name="a" icon-size="16px" checked-color="#F59A23">
                        <span style="color:#A0A0A0">我已阅读并同意</span>
                        <span style="color:#A0A0A0" @click.stop.prevent="$router.push('/yonghuxieye/details')">《日恒健康用户协议》</span>
                    </van-checkbox>
                </van-checkbox-group>
            </div>
        </div>

        <!-- 选择激活方式 -->
        <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
            <van-picker :columns="columns" :model-value="state.activateType" @confirm="onConfirm"
                @cancel="showPicker = false" />
        </van-popup>

        <van-dialog v-model:show="state.dialogShow" title="提示" :showConfirmButton="false">
            <div class="flex-v-center mt-30">
                <div class="color-gary f16" v-if="jifengData && jifengData.number">您成功领取{{jifengData.number}}张积分券！</div>
                <div class="color-gary f16" v-if="jifengData && jifengData.deductibleAmount">您成功领取{{jifengData.deductibleAmount}}抵扣金！</div>
                <div class="pt-40 pb-29" @click="onDialogClose">
                    <van-button round class="pt-40 pb-29" color="#F59A23"
                        style="height: 42px; width:120px;">确定</van-button>
                </div>
            </div>
        </van-dialog>

        <!-- 支付确认提示 -->
        <van-dialog v-model:show="state.dialogPayShow" title="提示" :showConfirmButton="false">
            <div class="flex-v-center mt-30">
                <div class="color-gary f16 px-15">开启本服务，需支付<span style="color:#f30">{{payInfo.totalPrice}}</span>元权益服务费。是否继续?</div>
                <div class="pt-40 pb-29 flex-h-between">
                    <van-button round class="pt-40 pb-29" color="#666666"
                    style="height: 42px; width:110px; margin-right:10px;" @click="onDialogPayClose">取消</van-button>
                    <van-button round class="pt-40 pb-29" color="#F59A23"
                        style="height: 42px; width:110px;margin-left:10px;" @click="payFn">确定</van-button>
                </div>
            </div>
        </van-dialog>

        <!-- <van-popup v-model:show="cartCodeShow" position="bottom" closeable>
            <inputKey @my-key="input_key" />
        </van-popup> -->

        <!-- 输入车牌号 -->
        <van-popup v-model:show="state.cartCodeShow" round position="bottom" :style="{ height: '51%' }">
            <Keybords @sendCarNumber="getcrNumber"></Keybords>
        </van-popup>


    </div>
</template>

<style lang="less" scoped>
.bind-phone {
    // height: 100vh;
    border-radius: 30px;
    padding: 46px 30px 80px;
}

.logo {
    width: 100px;
    height: 100px;
    display: block;
    margin: 0 auto;
}

:deep(.van-field) {
    height: 44px;
    margin-bottom: 20px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    color: red;
}

.code-button {
    font-size: 14px;
    font-weight: 400;
    color: #fbd3a1;
    line-height: 14px;
}

.bind-btn {
    margin-top: 40px;
    height: 44px;
    background: #BFBCB8;
    color: #fff;
    border-radius: 22px;

    display: flex;
    justify-content: center;
    align-items: center;

    font-size: 16px;
    font-weight: 500;
    // opacity: 0.5;

    &.can {
        // opacity: 1;
        background: #F59A23;
    }
}
</style>
